package io.renren.modules.forYoung.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.forYoung.entity.NewsEntity;
import io.renren.modules.forYoung.service.NewsService;
import io.renren.modules.oss.entity.MysqlOssEntity;
import io.renren.modules.sys.entity.SysMenuEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("forYoung/news")
public class NewsController {
    @Autowired
    NewsService newsService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public List<NewsEntity> list(){
        List<NewsEntity> menuList = newsService.getMyNewsList(null);
        return menuList;
    }

    /**
     * 列表
     */
    @RequestMapping("/delete")
    public R delete(Integer id){
        int re=newsService.delete(id);
        if(re==0)
            return R.ok();
        else
            return R.ok("请删除文件夹中文件",101);
    }


    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        String uuid= UUID.randomUUID().toString();
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        try {
            Map<String, Object> param = new HashMap<String, Object>();

            param.put("name", uuid+file.getOriginalFilename());
            param.put("buffer", file.getBytes());
            newsService.upload(param);
        } catch (Exception e) {
            System.out.println(e);
        }
        return R.ok().put("url","http://106.14.146.131:280/zte-api/api/young/file/"+uuid+file.getOriginalFilename());
    }


    /**
     * 读取文件
     */
    @RequestMapping("/file/{name}")
    public @ResponseBody
    Map<String,Object>  getimage(@PathVariable("name")String name, HttpServletResponse response) throws Exception {
        MysqlOssEntity m=newsService.getImgByName(name);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + m.getName());
        ServletOutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象
        toClient.write(m.getImg());  //输出数据
        toClient.flush();
        toClient.close();
        return null;
    }

}
